package com.Final.hj;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class FriendNew extends Fragment {

    private static final int GETNEWINFO = 1;
    private final int DELAY = 6000;
    private  String status = "-1";


    private ListView new_f_List;
    private List<FriendNewData> friend_new_list = new ArrayList<>();
    private ArrayAdapter adapter;
    private Context friendNewContent;
    FriendNewData newListItem;
    //自己的id
    private String myId;
    private Button rejectBtn, solvBbtn;
    private EditText set_letter;
    private String  letter_name;//备注
    private int  clickItem;//点击项

    //定时器
    private Timer timer;
    private TimerTask task;

    @Override
    public void onAttach(final Context context) {
        super.onAttach(context);
        friendNewContent = context;
        getTimer();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_friend_add, container, false);
        initView(view);


        new_f_List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                newListItem = friend_new_list.get(position);
                clickItem = position;
                //满足这三个条件才能点击弹窗c
                if(myId.equals(newListItem.getId()) && newListItem.getStatus().equals("1") && status.equals("-1")){
                    //说明别人添加我 可以弹窗
                    newDlg();
                }
            }
        });

        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden){
        super.onHiddenChanged(hidden);
        if(hidden){//结束的时候使用
            //停止定时器
            timer.cancel();
            timer = null;
            task.cancel();
            task = null;
            return;
        }else{
            //这里启动定时器
            getTimer();
        }
    }

    public void newDlg(){

        AlertDialog.Builder builder = new AlertDialog.Builder(friendNewContent);
        View view = View.inflate(friendNewContent, R.layout.new_friend_opa, null);

        //设置页面
        builder.setView(view);

        final AlertDialog dlg = builder.create();
        //初始化相应的内容
        initSelectView(view);

        //同意
        solvBbtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                //发送请求
                changeStatus(dlg, true);
                status = "2";

            }
        });

        //拒绝
        rejectBtn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                changeStatus(dlg, false);
                status = "0";
            }
        });

        dlg.show();
    }

    //定时器
    public void getTimer(){
        if(timer != null && task != null){
            return;
        }

        timer = new Timer();

        task = new TimerTask() {
            @Override
            public void run() {
                try {
                    //可以使用一个Handler对象，将定时消息传递到界面线程
                    friendSeach();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        timer.schedule(task, 0, DELAY);
    }

    //初始化 fragment变量
    public void initView(View v){
        new_f_List = (ListView) v.findViewById(R.id.new_friend);
    }

    //初始化弹窗
    public void initSelectView(View v){
        rejectBtn = (Button) v.findViewById(R.id.new_add_reject);
        solvBbtn = (Button) v.findViewById(R.id.new_add_solve);
        set_letter = (EditText) v.findViewById(R.id.new_add_edit);
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            switch (msg.what){
                case GETNEWINFO:
                    adapter = new FriendNewAdapter(friendNewContent, R.layout.new_friend_adapter, friend_new_list);
                    new_f_List.setAdapter(adapter);
                    break;
            }
        }
    };

    public void friendSeach(){
        myId = LoginSQLManger.getInstance(friendNewContent).queryAll().getMyId();
        //启动线程 发送请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://192.168.43.124:8080/gfriend?myId="+ myId)
                            .build();

                    //这里发送同步请求即可
                    Response response = client.newCall(request).execute();

                    String string = response.body().string();

                    //解析数据
                    parseData(string);

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //发送请求 修改数据status
    public void changeStatus(final AlertDialog dlg, boolean flag){
        if(flag){
            letter_name = set_letter.getText().toString().trim();
            if(letter_name.isEmpty()){
                Toast.makeText(friendNewContent, "请输入对方备注", Toast.LENGTH_SHORT).show();
                return;
            }else{
                //此时页面显示这里修改最新的备注 此时不一定是0
                friend_new_list.get(clickItem).setMyUname(letter_name);
                //更新界面
                updataPage();
                dlg.dismiss();
            }
        }else{
            letter_name = newListItem.getMyUname();
            dlg.cancel();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();

                    RequestBody requestBody = new FormBody.Builder()
                            .add("id", myId)
                            .add("myId", newListItem.getMyId())
                            .add("myUname", letter_name)
                            .add("status", status)
                            .build();

                    Request request = new Request.Builder()
                            .url("http://192.168.43.124:8080/cfriend")
                            .post(requestBody)
                            .build();

                    Response response = client.newCall(request).execute();
                    String string = response.body().string();


                    handle(string);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }).start();
    }
    public void parseData(String strJson) {


        //没有数据 不要往下执行了
        if(strJson.length() <= 0){
            return;
        }

        //清空集合
        friend_new_list.clear();

        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(strJson).getAsJsonArray();
        Gson gson = new Gson();

        for (JsonElement user : jsonArray) {
            //使用GSON，直接转成Bean对象
            FriendNewData userBean = gson.fromJson(user, FriendNewData.class);
            friend_new_list.add(userBean);
        }


        //更新界面
        updataPage();
    }

    public void handle(String string){
            if(string.equals("0")){
                string = "操作失败";
            }else{
               if(status.equals("0")){
                   string = "您已拒绝";
               } else{
                   string = "您已同意";
               }
            }

            Looper.prepare();
            Toast.makeText(friendNewContent, string, Toast.LENGTH_LONG).show();
            Looper.loop();
    }

    public void updataPage(){
        //此时发送msg 更新ui
        Message message = new Message();
        message.what = GETNEWINFO;
        handler.sendMessage(message);
    }
}
